package com.sxm.yiwei.pinche;

import android.app.ProgressDialog;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.sxm.yiwei.MainActivity;
import com.sxm.yiwei.R;
import com.sxm.yiwei.activitis.MineMember;
import com.sxm.yiwei.adapters.pinche.PassengerOrdersAdapter;
import com.sxm.yiwei.base.BaseActivity;
import com.sxm.yiwei.beans.pinche.Order;
import com.sxm.yiwei.beans.pinche.PassengerOrder;
import com.sxm.yiwei.constant.Common;
import com.sxm.yiwei.constant.Constant;
import com.sxm.yiwei.tools.BookPayActivity;
import com.sxm.yiwei.utils.DateUtil;
import com.sxm.yiwei.utils.HandleDataUtil;
import com.sxm.yiwei.views.CenterDialog;
import com.sxm.yiwei.views.MyListview;
import com.sxm.yiwei.views.PullToRefreshView;

import java.util.ArrayList;
import java.util.Date;

public class PassengerOrdersActivity extends BaseActivity implements View.OnClickListener, CenterDialog.OnCenterItemClickListener{
    private RelativeLayout rl_back;
    private TextView tv_title;
    private ImageView iv_search;
    private ImageView iv_home;
    private MyListview listView;
    private Order order;
    private ArrayList<PassengerOrder> passengerOrders;
    private PassengerOrdersAdapter adapter;
    private LinearLayout ll_grade;
    private ImageView iv_icon;
    private TextView tv_grade;
    private TextView tv_baojia;
    private TextView tv_upgrade;
    private ProgressDialog progressDialog;
    private int type=Constant.LONG;
    private int page=1;
    private int failure_code;
    private CenterDialog centerDialog;
    private PassengerOrder passengerOrder;
    private PullToRefreshScrollView refresh_view;
    private int http_flag=Constant.DEFAULT;
    private int temper_page=1;
    private RelativeLayout rl_no_data;

    @Override
    public void setContentView() {
        setContentView(R.layout.activity_passenger_orders);

    }

    @Override
    public void initView() {
        rl_back = (RelativeLayout)findViewById(R.id.rl_back);
        tv_title = (TextView)findViewById(R.id.tv_title);
        iv_search = (ImageView)findViewById(R.id.iv_search);
        iv_home = (ImageView)findViewById(R.id.iv_home);
        listView = (MyListview) findViewById(R.id.listView);

        ll_grade = (LinearLayout)findViewById(R.id.ll_grade);
        iv_icon = (ImageView)findViewById(R.id.iv_icon);
        tv_grade = (TextView)findViewById(R.id.tv_grade);
        tv_baojia = (TextView)findViewById(R.id.text21);
        tv_upgrade = (TextView)findViewById(R.id.tv_upgrade);
        rl_no_data = (RelativeLayout)findViewById(R.id.rl_no_data);
        refresh_view = (PullToRefreshScrollView)findViewById(R.id.refresh_view);
        refresh_view.setMode(PullToRefreshBase.Mode.BOTH);
        ScrollView scrollView = refresh_view.getRefreshableView();
        scrollView.smoothScrollTo(0,0);


    }

    @Override
    public void initListener() {
        rl_back.setOnClickListener(this);
        iv_search.setOnClickListener(this);
        iv_home.setOnClickListener(this);
        tv_upgrade.setOnClickListener(this);
        refresh_view.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
            @Override
            public void onPullDownToRefresh(final PullToRefreshBase<ScrollView> refreshView) {
                page=1;
                temper_page=page;
                http_flag=Constant.REFRESH;
                refresh_view.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getPassengerReleaseList();
                        refreshView.onRefreshComplete();
                    }
                },2000);
            }

            @Override
            public void onPullUpToRefresh(final PullToRefreshBase<ScrollView> refreshView) {
                page++;
                temper_page=page;
                http_flag=Constant.LOAD_MORE;
                refresh_view.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getPassengerReleaseList();
                        refreshView.onRefreshComplete();
                    }
                },2000);
            }
        });
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                //showToast(""+i);
                passengerOrder = passengerOrders.get(i);
                Intent intent = new Intent(PassengerOrdersActivity.this, PassengerOrderDetailActivity.class);
                intent.putExtra("passengerOrder",passengerOrder);
                intent.putExtra("type",type);
                startActivity(intent);

            }
        });

    }

    private void hostRobFormOrder() {
        JSONObject object = new JSONObject();
        object.put("serviceId", passengerOrder.getService_id());//服务主键
        object.put("ownerId", getHeadInfo().getUserId());//车主主键
        object.put("passerId", passengerOrder.getPasser_id());//乘客主键
        object.put("pinLoseAccount", passengerOrder.getLoss_money()+"");//爽约金
        httpPost(Common.HOST + Common.HOST_ROB_ORDER,object, Constant.HOST_ROB_ORDER);
    }

    @Override
    public void initData() {
        order = (Order) getIntent().getSerializableExtra("search_param");
        type=order.getStyle();
        switch (order.getStyle()){
            case Constant.LONG:
                tv_title.setText("我是车主—长途");
                ll_grade.setVisibility(View.GONE);
                break;
            case Constant.CITY:
                tv_title.setText("我是车主—同城");
                ll_grade.setVisibility(View.GONE);
                break;
            case Constant.TRAVEL:
                tv_title.setText("我是车主—旅游");
                ll_grade.setVisibility(View.GONE);
                break;
            case Constant.LONG_HURRY:
                tv_title.setText("我是车主—长途急件");
                ll_grade.setVisibility(View.VISIBLE);
                break;
        }
        passengerOrders=new ArrayList<>();
        adapter = new PassengerOrdersAdapter(this,passengerOrders);
        adapter.setOnButtonClickListener(new PassengerOrdersAdapter.OnButtonClickListener() {
            @Override
            public void onWeiClick(int position) {
                showToast("暂未开放");
            }

            @Override
            public void onRobClick(int position) {
                passengerOrder = passengerOrders.get(position);
                JSONObject object = new JSONObject();
                object.put("serviceId", passengerOrder.getService_id());//服务主键
                object.put("ownerId", getHeadInfo().getUserId());//车主主键
                object.put("passerId", passengerOrder.getPasser_id());//乘客主键
                object.put("pinLoseAccount", passengerOrder.getLoss_money()+"");//爽约金
                httpPost(Common.HOST + Common.HOST_ROB_ORDER,object,Constant.HOST_ROB_ORDER);

            }
        });
        listView.setAdapter(adapter);


        getPassengerReleaseList();
    }

    private void getPassengerReleaseList() {
        JSONObject object = new JSONObject();
        object.put("pinServiceKinds",""+type);
        object.put("pinStartPoint", order.getStart_place());
        object.put("pinEndPoint",order.getEnd_place());
        if (TextUtils.isEmpty(order.getDepart_time())){

        }else {
            if (!TextUtils.isEmpty(order.getStart_time())&&!TextUtils.isEmpty(order.getEnd_time())){
                object.put("leaveOffTime",order.getDepart_time());
                object.put("leftLeaveOffTime",order.getStart_time());
                object.put("rightLeaveOffTime",order.getEnd_time());
            }else {
                object.put("leaveOffTime",order.getDepart_time());
            }
        }

        object.put("pageNo",page+"");
        object.put("pageSize","20");
        httpGet(Common.HOST+Common.SEARCH_PASSENGER_SURVICE,object, Constant.SEARCH_PASSENGER_SURVICE);
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()){
            case R.id.iv_search:
                break;
            case R.id.iv_home:
                startActivity(new Intent(this, MainActivity.class));
                finish();
                break;
            case R.id.tv_upgrade:
                break;
        }
    }


    @Override
    public void OnCenterItemClick(CenterDialog dialog, View view) {
        switch (view.getId()){
            case R.id.dialog_sure:
                switch (failure_code){
                    case Constant.NAME_VERIFYING:
                        dialog.cancel();

                        break;
                    case Constant.NAME_NOT_VERIFY:
                        startActivity(new Intent(this, MineMember.class));
                        break;
                    case Constant.NAME_VERIFY_FALSE:
                        startActivity(new Intent(this, MineMember.class));

                        break;
                    case Constant.CAR_VERIFYING:
                        dialog.cancel();

                        break;
                    case Constant.CAR_VERIFY_FALSE:
                        startActivity(new Intent(this,CarVerifyActivity.class));
                        break;
                    case Constant.CAR_NOT_VERIFY:
                        startActivity(new Intent(this,CarVerifyActivity.class));

                        break;
                    default:
                        break;
                }
                break;
            default:
                dialog.cancel();
                break;
        }
    }

    @Override
    public void onError(Throwable ex) {
        super.onError(ex);
    }

    @Override
    public void onSuccess(String result, String fromWhere) {
        super.onSuccess(result,fromWhere);
        com.alibaba.fastjson.JSONObject obj = JSON.parseObject(result);
        if (fromWhere.equals(Constant.SEARCH_PASSENGER_SURVICE)){
            if (page==1){
                passengerOrders.clear();
            }else {
                if (page>temper_page){//加载更多之前有失败的网络请求操作

                }
            }
            JSONArray data = obj.getJSONArray("data");
            for (int i = 0; i < data.size(); i++) {
                JSONObject jsonObject = data.getJSONObject(i);
                PassengerOrder passengerOrder = new PassengerOrder();
                passengerOrder.setDepart_time(DateUtil.times(jsonObject.getLong("leaveOffTime")));
                passengerOrder.setIcon(jsonObject.getString("passerAvatar"));
                passengerOrder.setPasser_id(jsonObject.getString("passerId"));
                passengerOrder.setPhone(jsonObject.getString("passerMobile"));
                passengerOrder.setNickname(jsonObject.getString("passerNickName"));
                passengerOrder.setSeats_need(jsonObject.getIntValue("passerRequireSeats"));
                passengerOrder.setStart_time(DateUtil.times(jsonObject.getLong("pinCreateTime")));
                passengerOrder.setEnd_place(jsonObject.getString("pinEndPoint"));
                passengerOrder.setPrice(jsonObject.getDouble("pinServiceAccount"));
                passengerOrder.setService_code(jsonObject.getString("pinServiceCode"));
                passengerOrder.setStyle(jsonObject.getIntValue("pinServiceKinds"));
                passengerOrder.setStart_place(jsonObject.getString("pinStartPoint"));
                passengerOrder.setDistance(jsonObject.getDouble("pinTotalDistance"));
                passengerOrder.setService_id(jsonObject.getString("serviceId"));
                passengerOrder.setWords(jsonObject.getString("pinLeaveWords"));
                passengerOrder.setTotal_price(passengerOrder.getPrice()*passengerOrder.getSeats_need());
                passengerOrder.setLoss_money(HandleDataUtil.saveToPoint2(passengerOrder.getTotal_price()*0.1));
                passengerOrders.add(passengerOrder);
            }
            if (passengerOrders.size()>0){
                rl_no_data.setVisibility(View.GONE);
                refresh_view.setVisibility(View.VISIBLE);

            }else {
                rl_no_data.setVisibility(View.VISIBLE);
                refresh_view.setVisibility(View.GONE);
            }
            adapter.notifyDataSetChanged();

        }else if (fromWhere.equals(Constant.HOST_ROB_ORDER)){
            JSONObject data = obj.getJSONObject("data");
            Intent intent = new Intent(PassengerOrdersActivity.this, BookPayActivity.class);
            if (!data.getString("orderId").equals("")){
                intent.putExtra("orderCode",data.getString("orderId"));//orderId
            }else {
                showToast("orderId为空");
                return;
            }
            intent.putExtra("amount",passengerOrder.getLoss_money()+"");//爽约金
            intent.putExtra("from", Constant.HOST_ROB_PAY);
            intent.putExtra("id",passengerOrder.getService_id());
            intent.putExtra("alipay",Common.HOST_SEARCH_ALIPAY);
            intent.putExtra("yivipay",Common.HOST_SEARCH_RESTPAY);
            startActivity(intent);
        }
    }

}
